05 / 05

When would you use a struct with methods vs a map in Go?

Structs offer compile-time safety, better performance, IDE support, and method attachment for known fields. Maps are for dynamic or unknown keys at runtime.

Use structs when
  1. 1

    Field names are known at compile time — compile-time typo safety

  2. 2

    You need to attach methods and implement interfaces

  3. 3

    Performance matters — struct field access is direct memory offset, map access involves hashing

  4. 4

    Working with JSON APIs — struct tags control serialization cleanly

  5. 5

    You want IDE autocompletion and refactoring support

Use maps when
  1. 1

    Keys are only known at runtime (user-supplied, config-driven)

  2. 2

    Sparse data where most fields would be zero-valued

  3. 3

    Implementing caches, lookup tables, or frequency counters

  4. 4

    Processing arbitrary JSON blobs of unknown schema

  5. 5

    Building dynamic query parameters or HTTP header collections

Struct vs map comparison